<template>
  <div>
    <!-- 1.0 面包屑 要在父组件中接收子组件传过来的事件-->
    <my-breadcrumb  level1="用户管理" level2="用户分类"></my-breadcrumb>
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <!-- 2.0 搜索框 & 添加用户按钮 -->
    <el-input class="search" placeholder="请输入要搜索的内容" v-model="query">
      <el-button slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <el-button style="margin-left:5px;" type="success" plain @click="dialogVisible4Add = true">添加用户</el-button>
    <!-- 3.0商品列表 -->
    <el-table :data="userList" border stripe style="width: 100%">
      <el-table-column prop="username" label="序号" type="index" width="60"></el-table-column>
      <el-table-column prop="username" label="姓名" width="80"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="140"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="130"></el-table-column>
      <el-table-column prop="role_name" label="角色" width="100">
        <!-- <el-switch v-model="value3" active-text="" inactive-text=""></el-switch> -->
      </el-table-column>
      <el-table-column label="用户状态" width="180">
        <template slot-scope="scope">
          <!-- scope.row 就拿到当前遍历的那一行数据 给switch注册change事件-->
          <el-switch
            @change="changeStatus(scope.row.mg_state,scope.row.id)"
            v-model="scope.row.mg_state"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="mini"
            plain
            @click="editUser(scope.row.id)"
          ></el-button>
          <el-button
            size="mini"
            icon="el-icon-delete"
            type="danger"
            @click="deleteUser(scope.row.id)"
            plain
          ></el-button>
          <el-button
            size="mini"
            icon="el-icon-check"
            type="warning"
            plain
            @click="checkUser(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 4.0 分页条 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 5.0新增用户对话框 -->
    <el-dialog title="新增用户" :visible.sync="dialogVisible4Add" width="50%">
      <el-form :model="addUserObj" :rules="rules" ref="addUserRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserObj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserObj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4Add = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 6.0 修改用户对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogVisible4Edit" width="50%">
      <el-form :model="editUserObj" :rules="rules" ref="editUserRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserObj.username" style="width:100px" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4Edit = false">取 消</el-button>
        <el-button type="primary" @click="editUser2">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 7.0授权角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible4Check" width="50%">
      <el-form  label-width="100px">
        <el-form-item label="当前用户名">
         <span>{{username}}</span>
        </el-form-item>
        <el-form-item label="请选择角色">
          <el-select v-model="selectRoles" placeholder="请选择角色列表"
           @change="selectChange">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4Check = false">取 消</el-button>
        <el-button type="primary" @click="checkUser2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//导入面包屑子组件
import MyBreadcrumb from '../subcomponents/MyBreadcrumb'
export default {
  //注册子组件
  components: {
    'my-breadcrumb': MyBreadcrumb
  },
  data() {
    return {
      query: '', //查询关键字
      pagenum: 1, //查询页码
      pagesize: 5, //查询页容量
      userList: [], //用户列表
      total: 0, //总条数
      dialogVisible4Add: false,
      dialogVisible4Edit: false,
      dialogVisible4Check: false,
      addUserObj: {
        // 添加用户
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserObj: {
        // 修改用户
        id: '',
        email: '',
        mobile: ''
      },
      checkUserObj: [],
      username: '', //展示的用户名
      rolesList: [], //角色列表
      selectRoles: '',
      roleId: null, //后台需要
      userId: null,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  created() {
    //生命周期钩子
    this.getUserListData()
  },
  methods: {
    //发送请求  获取用户列表数
    getUserListData() {
      // console.log(params)
      this.$axios
        .get(`users`, {
          params: {
            pagenum: this.pagenum,
            pagesize: this.pagesize,
            query: this.query
          }
        })
        .then(res => {
          //赋值给模型
          // console.log(res)
          this.userList = res.data.data.users
          //赋值总条数
          this.total = res.data.data.total
        })
    }, //当页面改变的时候触发
    handleSizeChange(pagesize) {
      this.pagesize = pagesize
      this.getUserListData()
    },
    handleCurrentChange(pagenum) {
      this.pagenum = pagenum
      this.getUserListData()
    },
    addUser() {
      // 拿到el-form这个表单
      this.$refs.addUserRef.validate(valid => {
        if (valid) {
          // 验证通过
          this.$axios.post(`users`, this.addUserObj).then(res => {
            if (res.data.meta.status === 201) {
              // 隐藏对话框
              this.dialogVisible4Add = false

              // 提示
              this.$message({
                type: 'success',
                message: res.data.meta.msg
              })

              // 重新查询列表
              this.getUserListData()
            }
          })
        }
      })
    },
    //swith开关事件,改变状态值
    changeStatus(state, userId) {
      // console.log(state,userId)
      //获取好当前值就发送请求
      this.$axios.put(`users/${userId}/state/${state}`).then(res => {
        // console.log(res)
        if (res.data.meta.status !== 200) {
          //登陆失败
          this.$message.error(res.data.meta.msg)
        } else {
          this.$message({
            message: '修改状态成功',
            type: 'success'
          })
        }
      })
    }, //编辑用户信息,弹出修改框
    editUser(userId) {
      console.log(userId)
      this.$axios.get(`users/${userId}`).then(res => {
        console.log(res)
        //赋值给模型,弹出修改框,才能填充上值
        this.editUserObj = res.data.data
        //弹出修改的对话框
        this.dialogVisible4Edit = true
      })
    },
    //修改用户信息并提交
    editUser2() {
      this.$axios
        .put(`users/${this.editUserObj.id}`, this.editUserObj)
        .then(res => {
          if (res.data.meta.status !== 200) {
            //提示修改失败
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message({
              message: '修改用户信息成功',
              type: 'success'
            })
            //关闭对话框
            this.dialogVisible4Edit = false
            //刷新列表
            this.getUserListData()
          }
        })
    },
    //删除用户信息
    deleteUser(userId) {
      this.$confirm('是否要删除页面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$axios.delete(`users/${userId}`).then(res => {
          if (res.data.meta.status !== 200) {
            //提示删除失败
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message({
              message: '删除用户信息成功',
              type: 'success'
            })
          }
          //刷新列表
          this.getUserListData()
        })
      })
    },
    //用户授权角色 并弹框
    checkUser(user) {
      this.userId = user.id
      this.username = user.username
       // 设置选中的角色
      this.selectRoles = user.role_id
      this.$axios.get(`roles`).then(res => {
        console.log(res)
        //赋值给模型,弹出修改框,才能填充上值
        this.rolesList = res.data.data
        //弹出修改的对话框
        this.dialogVisible4Check = true
      })
    },
    selectChange(roleId) {
      this.roleId = roleId
    },
    //给用户最终授权角色
    checkUser2() {
      if (!this.roleId) {
        this.$message.error('必须要选中一个角色哦')
        return
      }
      this.$axios
        .put(`users/${this.userId}/role`, {
          
            rid: this.roleId
          
        })
        .then(res => {
          if (res.data.meta.status !== 200) {
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message({
              message: '授权角色成功',
              type: 'success'
            })
            this.dialogVisible4Check = false
            this.getUserListData()
          }
        })
    },
    //父组件通过监听子组件的事件接收值
    accessEvent(val){
      console.log(val)
    }
  }
}
</script>

<style scoped>
/* .el-breadcrumb {
  background-color: #d3dce6;
  height: 50px;
  line-height: 50px;
  padding-left: 10px;
} */
.el-pagination {
  background-color: #d3dce6;
  padding-top: 10px;
  height: 35px;
  line-height: 35px;
}
.search {
  width: 300px;
}
</style>

